﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml;
using Microsoft.Extensions.Configuration;

namespace _067.自定义配置系统读取
{
	internal class FxConfigProvider : FileConfigurationProvider
	{

		public override void Load(Stream stream)
		{
			var data = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
			XmlDocument xmlDoc = new XmlDocument();
			xmlDoc.Load(stream);

			var csNodes = xmlDoc.SelectNodes("/configuration/connectionStrings/add");
			if (csNodes != null)
			{
				foreach (var xmlNode in csNodes.Cast<XmlNode>())
				{
					string name = xmlNode.Attributes["name"].Value;
					string connectionString = xmlNode.Attributes["connectionString"].Value;

					data[$"{name}:connectionString"] = connectionString;
					var attProviderName = xmlNode.Attributes["providerName"];
					if (attProviderName != null)
					{
						data[$"{name}:providerName"] = attProviderName.Value;
					}
				}
			}
				

			var asNodes = xmlDoc.SelectNodes("/configuration/appSettings/add");
			foreach (var xmlNode in asNodes.Cast<XmlNode>())
			{
				string key = xmlNode.Attributes["key"].Value;
				key = key.Replace(".", ":");
				string value = xmlNode.Attributes["value"].Value;
				data[key] = value;
			}

		}

		public FxConfigProvider(FileConfigurationSource source) : base(source)
		{

		}
	}
}
